using Dapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.PurchasingManagement.PurchaseOrders;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Application.Handler.ERP.PurchasingManagement.PurchaseOrders
{
    /// <summary>
    /// 批量修改采购订单单据状态（仅允许：开立 -> 审核 或 开立 -> 撤回）
    /// </summary>
    public class BatchChangePurchaseOrderStatusCommandHandler : IRequestHandler<BatchChangePurchaseOrderStatusCommand, APIResult<int>>
    {
        private static readonly string[] AllowedTargets = new[] { "审核", "撤回" };

        private readonly IDbConnectionFactory _connectionFactory;
        private readonly ILogger<BatchChangePurchaseOrderStatusCommandHandler> _logger;

        public BatchChangePurchaseOrderStatusCommandHandler(
            IDbConnectionFactory connectionFactory,
            ILogger<BatchChangePurchaseOrderStatusCommandHandler> logger)
        {
            _connectionFactory = connectionFactory;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchChangePurchaseOrderStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "未指定要修改的ID集合", Data = 0 });
                }
                if (string.IsNullOrWhiteSpace(request.TargetStatus) || !AllowedTargets.Contains(request.TargetStatus))
                {
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "仅允许将状态修改为: 审核 或 撤回", Data = 0 });
                }

                using var conn = _connectionFactory.CreateConnectionWithRetry();
                using var tran = conn.BeginTransaction();

                // 仅允许从 开立 变更
                // 当目标为 审核：同时更新 auditDate = 当前时间
                var sql = request.TargetStatus == "审核"
                    ? "UPDATE PurchaseOrderInfo SET docStatus = @TargetStatus, auditDate = @Now WHERE IsDeleted = 0 AND docStatus = @Open AND Id IN @Ids"
                    : "UPDATE PurchaseOrderInfo SET docStatus = @TargetStatus WHERE IsDeleted = 0 AND docStatus = @Open AND Id IN @Ids";

                var affected = conn.Execute(sql, new { TargetStatus = request.TargetStatus, Now = DateTime.Now, Open = "开立", request.Ids }, tran);

                tran.Commit();

                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Success,
                    Msg = $"批量状态修改完成，影响 {affected} 条记录",
                    Data = affected
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量修改采购订单状态失败: {Message}", ex.Message);
                return Task.FromResult(new APIResult<int>
                {
                    Code = APIEnums.Error,
                    Msg = "批量修改采购订单状态异常",
                    Data = 0
                });
            }
        }
    }
}
